package com.anche.cywebnew.Utils.HikUtil;

import com.anche.cywebnew.DTO.HikBaseDTO;
import com.anche.cywebnew.Pojo.businessManager.CyDataVideoInfo;
import com.sun.jna.NativeLong;
import com.sun.jna.ptr.IntByReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;
import java.util.Date;

public class VideoUtil extends CommonUtil {

    private static final Logger logger = LoggerFactory.getLogger(VideoUtil.class);

    public boolean doDownload(NativeLong lUserID,NativeLong ch, Date kssj, Date jssj, String fileName) throws InterruptedException {
        boolean isDownload = false;
        NativeLong m_lLoadHandle;
        HCNetSDK.NET_DVR_TIME struStartTime = new HCNetSDK.NET_DVR_TIME();
        HCNetSDK.NET_DVR_TIME struStopTime = new HCNetSDK.NET_DVR_TIME();
        DateToDVRTime(kssj, struStartTime);
        DateToDVRTime(jssj, struStopTime);
        m_lLoadHandle = hCNetSDK.NET_DVR_GetFileByTime(lUserID, ch, struStartTime, struStopTime, fileName);
        if (m_lLoadHandle.intValue() >= 0) {
            hCNetSDK.NET_DVR_PlayBackControl(m_lLoadHandle, HCNetSDK.NET_DVR_PLAYSTART, 0, null);
            logger.info("开始下载录像");
            IntByReference nPos = new IntByReference(0);
            do {
                hCNetSDK.NET_DVR_PlayBackControl(m_lLoadHandle, HCNetSDK.NET_DVR_PLAYGETPOS, 0, nPos);
                logger.info("检测录像下载进度：[{}]", nPos.getValue());
                Thread.sleep(5000);
            } while (nPos.getValue() < 100);
            logger.info("下载检测完成，[{}]", nPos.getValue());
            if (nPos.getValue() == 100) {
                hCNetSDK.NET_DVR_StopGetFile(m_lLoadHandle);
                logger.info("录像下载成功！");
                isDownload = true;
            } else if (nPos.getValue() > 100) {
                int code = hCNetSDK.NET_DVR_GetLastError();
                String msg = HikErrorUtil.getMsgByCode(code);
                logger.info("录像下载失败,错误码：[{}]，错误描述：[{}]", code, msg);
                resultMsg = String.format(errMsg, "录像下载失败", code, msg);
                hCNetSDK.NET_DVR_StopGetFile(m_lLoadHandle);
            }
        } else {
            int code = hCNetSDK.NET_DVR_GetLastError();
            String msg = HikErrorUtil.getMsgByCode(code);
            errMsg = String.format(errMsg, "录像开始下载失败", code, msg);
            logger.info("录像开始下载失败，错误码：[{}]，错误描述：[{}]", code, msg);
        }

        return isDownload;
    }

    private void DateToDVRTime(Date date, HCNetSDK.NET_DVR_TIME struStopTime) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        struStopTime.dwYear = calendar.get(Calendar.YEAR);
        struStopTime.dwMonth = calendar.get(Calendar.MONTH) + 1;
        struStopTime.dwDay = calendar.get(Calendar.DATE);
        struStopTime.dwHour = calendar.get(Calendar.HOUR_OF_DAY);
        struStopTime.dwMinute = calendar.get(Calendar.MINUTE);
        struStopTime.dwSecond = calendar.get(Calendar.SECOND);
    }
}
